<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

interface Props {
  visible: boolean;
  diagnosis?: string;
}

interface Emits {
  (e: 'update:visible',value: boolean): void;
  (e: 'success',template: any): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const selectedCategory = ref('common');
const selectedTemplate = ref<any>(null);

// 智能模板数据
const templates = ref([
  // 常见疾病
  {
    id: 'T001',
    category: 'common',
    name: '感冒发热',
    description: '适用于宠物感冒、发热等症状',
    tags: ['感冒', '发热', '上呼吸道'],
    diagnosis: '根据症状表现，初步诊断为上呼吸道感染，建议进行血常规检查确认。',
    treatment:
      '1. 对症治疗：退热、止咳、消炎\n2. 支持治疗：补充营养、保持休息\n3. 预防并发症：监测体温变化',
    medicines: [
      { id: 'M001', name: '阿莫西林胶囊', usage: '0.25g，每日2次，连用7天' },
      { id: 'M002', name: '布洛芬片', usage: '0.1g，每日3次，发热时服用' },
    ],
    advice:
      '1. 保持环境温暖，避免受凉\n2. 多饮水，清淡饮食\n3. 定期复查，观察病情变化',
    keywords: ['感冒', '发热', '流鼻涕', '咳嗽', '打喷嚏'],
  },
  {
    id: 'T002',
    category: 'common',
    name: '肠胃炎',
    description: '适用于呕吐、腹泻等消化道症状',
    tags: ['呕吐', '腹泻', '消化道'],
    diagnosis:
      '根据症状表现，初步诊断为急性肠胃炎，建议进行粪便检查排除寄生虫感染。',
    treatment:
      '1. 禁食禁水12-24小时\n2. 补液治疗：防止脱水\n3. 对症治疗：止吐、止泻',
    medicines: [
      { id: 'M003', name: '蒙脱石散', usage: '1袋，每日3次，饭前服用' },
      { id: 'M004', name: '益生菌', usage: '1袋，每日2次，饭后服用' },
    ],
    advice:
      '1. 逐步恢复饮食，从流质开始\n2. 避免油腻、刺激性食物\n3. 保持环境清洁',
    keywords: ['呕吐', '腹泻', '拉肚子', '肠胃', '消化不良'],
  },

  // 急诊处理
  {
    id: 'T003',
    category: 'emergency',
    name: '外伤处理',
    description: '适用于外伤、出血等紧急情况',
    tags: ['外伤', '出血', '急诊'],
    diagnosis: '根据外伤情况，评估伤口深度和出血程度，确定是否需要缝合。',
    treatment:
      '1. 清创消毒：彻底清洁伤口\n2. 止血处理：压迫止血或缝合\n3. 预防感染：使用抗生素',
    medicines: [
      { id: 'M005', name: '碘伏', usage: '外用消毒，每日2-3次' },
      { id: 'M006', name: '头孢克肟', usage: '0.1g，每日2次，连用5天' },
    ],
    advice: '1. 保持伤口清洁干燥\n2. 防止宠物舔舐伤口\n3. 定期换药复查',
    keywords: ['外伤', '出血', '伤口', '割伤', '撞伤'],
  },

  // 手术相关
  {
    id: 'T004',
    category: 'surgery',
    name: '绝育手术',
    description: '适用于公猫/公狗绝育手术',
    tags: ['绝育', '手术', '常规'],
    diagnosis: '建议进行绝育手术，预防生殖系统疾病，改善行为问题。',
    treatment:
      '1. 术前检查：血常规、生化检查\n2. 手术麻醉：全身麻醉\n3. 术后护理：消炎、止痛',
    medicines: [
      { id: 'M007', name: '头孢曲松', usage: '术前1小时，术后连用3天' },
      { id: 'M008', name: '布洛芬', usage: '术后止痛，每日2次' },
    ],
    advice: '1. 术后禁食6小时\n2. 保持手术部位清洁\n3. 限制活动，防止伤口裂开',
    keywords: ['绝育', '手术', '生殖', '发情', '行为问题'],
  },

  // 慢性疾病
  {
    id: 'T005',
    category: 'chronic',
    name: '糖尿病管理',
    description: '适用于糖尿病宠物的长期管理',
    tags: ['糖尿病', '慢性', '管理'],
    diagnosis: '根据血糖检测结果，确诊为糖尿病，需要长期胰岛素治疗。',
    treatment:
      '1. 胰岛素治疗：根据血糖调整剂量\n2. 饮食控制：低糖、高纤维\n3. 运动管理：适量运动',
    medicines: [
      { id: 'M009', name: '胰岛素', usage: '根据血糖调整，每日2次' },
      { id: 'M010', name: '二甲双胍', usage: '0.25g，每日2次' },
    ],
    advice: '1. 定期监测血糖\n2. 严格控制饮食\n3. 保持规律运动',
    keywords: ['糖尿病', '血糖', '多饮', '多尿', '消瘦'],
  },
]);

// 计算属性
const filteredTemplates = computed(() => {
  return templates.value.filter(
    (template) => template.category === selectedCategory.value,
  );
});

const analysisResult = computed(() => {
  if (!props.diagnosis) return '暂无诊断信息';

  const diagnosis = props.diagnosis.toLowerCase();
  const matchedKeywords = [];

  templates.value.forEach((template) => {
    template.keywords.forEach((keyword) => {
      if (diagnosis.includes(keyword)) {
        matchedKeywords.push(keyword);
      }
    });
  });

  if (matchedKeywords.length > 0) {
    return `检测到关键词: ${matchedKeywords.join(', ')}，推荐相关治疗方案`;
  }

  return '未检测到明确症状关键词，建议选择通用模板';
});

const smartRecommendations = computed(() => {
  if (!props.diagnosis) return [];

  const diagnosis = props.diagnosis.toLowerCase();
  const recommendations = [];

  templates.value.forEach((template) => {
    let score = 0;
    template.keywords.forEach((keyword) => {
      if (diagnosis.includes(keyword)) {
        score += 20; // 每个关键词匹配加20分
      }
    });

    if (score > 0) {
      recommendations.push({
        ...template,
        score: Math.min(score, 100),
      });
    }
  });

  // 按匹配度排序
  return recommendations.sort((a, b) => b.score - a.score).slice(0, 3);
});

// 方法
const onCategoryChange = () => {
  selectedTemplate.value = null;
};

const selectTemplate = (template: any) => {
  selectedTemplate.value = template;
};

const handleOk = () => {
  if (!selectedTemplate.value) {
    message.warning('请选择一个模板');
    return;
  }

  emit('success', selectedTemplate.value);
  emit('update:visible', false);

  // 重置选择
  selectedTemplate.value = null;
};

const handleCancel = () => {
  emit('update:visible', false);
  selectedTemplate.value = null;
};

// 监听模态框关闭
watch(
  () => props.visible,
  (visible) => {
    if (!visible) {
      selectedTemplate.value = null;
    }
  },
);
</script>

<template>
  <a-modal
    :open="visible"
    title="智能模板"
    width="1000px"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div class="intelligent-template-modal">
      <!-- 诊断信息分析 -->
      <div class="diagnosis-analysis" v-if="diagnosis">
        <h4>🔍 诊断信息分析</h4>
        <div class="analysis-content">
          <div class="diagnosis-text">{{ diagnosis }}</div>
          <div class="analysis-result">
            <span class="analysis-label">智能分析结果:</span>
            <span class="analysis-value">{{ analysisResult }}</span>
          </div>
        </div>
      </div>

      <!-- 模板分类 -->
      <div class="template-categories">
        <h4>模板分类</h4>
        <a-radio-group
          v-model:value="selectedCategory"
          @change="onCategoryChange"
        >
          <a-radio-button value="common">常见疾病</a-radio-button>
          <a-radio-button value="emergency">急诊处理</a-radio-button>
          <a-radio-button value="surgery">手术相关</a-radio-button>
          <a-radio-button value="chronic">慢性疾病</a-radio-button>
        </a-radio-group>
      </div>

      <!-- 智能推荐 -->
      <div class="smart-recommendations" v-if="smartRecommendations.length > 0">
        <h4>🤖 智能推荐</h4>
        <div class="recommendations-grid">
          <div
            v-for="recommendation in smartRecommendations"
            :key="recommendation.id"
            class="recommendation-card"
            :class="{ selected: selectedTemplate?.id === recommendation.id }"
            @click="selectTemplate(recommendation)"
          >
            <div class="recommendation-header">
              <span class="recommendation-name">{{ recommendation.name }}</span>
              <span class="recommendation-score"
                >匹配度: {{ recommendation.score }}%</span
              >
            </div>
            <div class="recommendation-desc">
              {{ recommendation.description }}
            </div>
            <div class="recommendation-tags">
              <a-tag
                v-for="tag in recommendation.tags"
                :key="tag"
                size="small"
                color="blue"
              >
                {{ tag }}
              </a-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 模板列表 -->
      <div class="template-list">
        <h4>智能模板</h4>
        <div class="template-grid">
          <div
            v-for="template in filteredTemplates"
            :key="template.id"
            class="template-card"
            :class="{ selected: selectedTemplate?.id === template.id }"
            @click="selectTemplate(template)"
          >
            <div class="template-name">{{ template.name }}</div>
            <div class="template-desc">{{ template.description }}</div>
            <div class="template-tags">
              <a-tag v-for="tag in template.tags" :key="tag" size="small">
                {{ tag }}
              </a-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 模板详情 -->
      <div class="template-details" v-if="selectedTemplate">
        <h4>模板详情</h4>
        <div class="template-content">
          <div class="content-section">
            <h5>诊断建议</h5>
            <div class="diagnosis-content">
              {{ selectedTemplate.diagnosis }}
            </div>
          </div>
          <div class="content-section">
            <h5>治疗方案</h5>
            <div class="treatment-content">
              {{ selectedTemplate.treatment }}
            </div>
          </div>
          <div class="content-section">
            <h5>推荐药品</h5>
            <div class="medicine-list">
              <div
                v-for="medicine in selectedTemplate.medicines"
                :key="medicine.id"
                class="medicine-item"
              >
                <span class="medicine-name">{{ medicine.name }}</span>
                <span class="medicine-usage">{{ medicine.usage }}</span>
              </div>
            </div>
          </div>
          <div class="content-section">
            <h5>医嘱建议</h5>
            <div class="advice-content">{{ selectedTemplate.advice }}</div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.intelligent-template-modal {
  max-height: 600px;
  overflow-y: auto;
}

.diagnosis-analysis {
  padding: 16px;
  margin-bottom: 24px;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  border-radius: 6px;
}

.diagnosis-analysis h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.analysis-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.diagnosis-text {
  padding: 8px;
  font-size: 12px;
  color: #666;
  background: white;
  border-radius: 4px;
}

.analysis-result {
  display: flex;
  gap: 8px;
  align-items: center;
}

.analysis-label {
  font-size: 12px;
  color: #666;
}

.analysis-value {
  font-size: 12px;
  font-weight: 600;
  color: #52c41a;
}

.template-categories {
  margin-bottom: 24px;
}

.template-categories h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.smart-recommendations {
  margin-bottom: 24px;
}

.smart-recommendations h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.recommendation-card {
  padding: 12px;
  cursor: pointer;
  background: #f0f9ff;
  border: 2px solid #e6f7ff;
  border-radius: 6px;
  transition: all 0.3s;
}

.recommendation-card:hover {
  border-color: #1890ff;
}

.recommendation-card.selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.recommendation-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.recommendation-name {
  font-weight: 600;
  color: #262626;
}

.recommendation-score {
  font-size: 12px;
  font-weight: 600;
  color: #1890ff;
}

.recommendation-desc {
  margin-bottom: 8px;
  font-size: 12px;
  line-height: 1.4;
  color: #666;
}

.recommendation-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.template-list {
  margin-bottom: 24px;
}

.template-list h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 12px;
  max-height: 200px;
  overflow-y: auto;
}

.template-card {
  padding: 12px;
  cursor: pointer;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  transition: all 0.3s;
}

.template-card:hover {
  border-color: #1890ff;
}

.template-card.selected {
  background: #e6f7ff;
  border-color: #1890ff;
}

.template-name {
  margin-bottom: 4px;
  font-weight: 600;
  color: #262626;
}

.template-desc {
  margin-bottom: 8px;
  font-size: 12px;
  line-height: 1.4;
  color: #666;
}

.template-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.template-details {
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.template-details h4 {
  margin: 0 0 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.template-content {
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.content-section {
  margin-bottom: 16px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.content-section h5 {
  margin: 0 0 8px;
  font-size: 13px;
  font-weight: 600;
  color: #666;
}

.diagnosis-content,
.treatment-content,
.advice-content {
  font-size: 12px;
  line-height: 1.5;
  color: #262626;
  white-space: pre-line;
}

.medicine-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.medicine-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px 8px;
  font-size: 12px;
  background: white;
  border-radius: 4px;
}

.medicine-name {
  font-weight: 600;
  color: #262626;
}

.medicine-usage {
  color: #666;
}
</style>
